//
//  ViewController.swift
//  mac-wky
//
//  Created by Apple on 2018/2/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Cocoa
import Alamofire
import Moya
import SwiftyJSON
import RxSwift

class ViewController: NSViewController {
    
    @IBOutlet weak var phoneTextField: NSTextField!
    @IBOutlet weak var pwdTextField: NSSecureTextField!
    @IBOutlet weak var loginButton: NSButton!
    
    let provider = MoyaProvider<ApiTarget>()
    let disBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let sessionid = App.getCookie(name: "sessionid")
        print("sessionid: \(sessionid)")
        
        
        let phoneText = phoneTextField.rx.text.orEmpty.asDriver()
        let pwdText = pwdTextField.rx.text.orEmpty.asDriver()
        let loginTap = loginButton.rx.tap.asDriver()
        
        let vm = LoginVM(input: (phoneText: phoneText,
                                 pwdText: pwdText,
                                 loginTap: loginTap))
        
        vm.isLoginEnabled.drive(loginButton.rx.isEnabled).disposed(by: disBag)
    }
    
    
    func login(phone: String, pwd: String) {
        
        // 清空cookie
        App.clearCookie()
        
        provider
            .request(.login(phone: phone, pwd: pwd)) {resp in
            print("---------- login phone: \(phone)  ---------")
            switch resp {
            case let .success(rst):
                if let rst = try? rst.mapJSON() {
                    print("rst: \(rst)")
                    
                    App.alert("登录成功")
                }

            case let .failure(error):
                print("err: \(error)")
            }
        }
    }
    
    func getListPeer(_ phone: String) {
        
        provider
            .request(.getListPeer(phone: "17191762176")) { [weak self] resp in
                print("---------- getListPeer phone: \(phone) ---------")
                switch resp {
                case let .success(rst):
                    guard let json = try? JSON(data: rst.data) else {
                        print("getListPeer-json为nil")
                        return
                    }
                    let rtn = json["rtn"].intValue
                    if rtn == 0 {
                        
                        let first = json["result"][1]["devices"][0]
                        let sn = first["device_sn"].stringValue
                        self?.getUserInfo(sn)
                        
                        
                        let pid = first["peerid"].stringValue
                        self?.remoteDlLogin(pid)
                    } else {
                        print("状态异常-\(rtn)")
                    }
                    
                case let .failure(err):
                    print("err: \(err)")
                }
        }
    }
    
    func getUserInfo(_ sn: String) {
        
        provider
            .request(.getUserInfo(sn: sn)) { resp in
                print("---------- getUserInfo sn: \(sn) ---------")
                switch resp {
                case let .success(rst):
                    guard let json = try? JSON(data: rst.data) else {
                        print("getUserInfo-json为nil")
                        return
                    }
                    
                    let yes_wkb = json["data"]["yes_wkb"].doubleValue
                    print("昨天-玩客币收益：\(yes_wkb)")
                case let .failure(err):
                    print("err: \(err)")
                }
        }
    }
    
    func remoteDlLogin(_ pid: String) {
        provider
            .request(.remoteDlLogin(pid: pid)) { [weak self] resp in
                print("---------- remoteDlLogin pid: \(pid) ---------")
                switch resp {
                case let .success(rst):
                    guard let json = try? JSON(data: rst.data) else {
                        print("remoteDlLogin-json为nil")
                        return
                    }
                    print(json)
                    let rtn = json["rtn"].intValue
                    if rtn == 0 {
                        self?.getRemoteDlList(pid: pid, type: "0")
                    } else {
                        print("状态异常-\(rtn)")
                    }
                    
                case let .failure(err):
                    print("err: \(err)")
                }
        }
    }
    
    func getRemoteDlList(pid: String, type: String) {
        
        provider
            .request(.getRemoteDlUrlList(pid: pid, type: type)) { [weak self] resp in
                print("---------- getRemoteDlList pid: \(pid) type: \(type) ---------")
                switch resp {
                case let .success(rst):
                    guard let json = try? JSON(data: rst.data) else {
                        print("getRemoteDlList-json为nil")
                        return
                    }
                    
                    print(json)
                    self?.urlResolve(pid: pid, url: "ftp://ygdy8:ygdy8@yg45.dydytt.net:4028/阳光电影www.ygdy8.net.忍者之国.BD.720p.日语中字.mkv")
                case let .failure(err):
                    print("err: \(err)")
                }
        }
    }
    
    func urlResolve(pid: String, url: String) {
        provider
            .request(.urlResolve(pid: pid, url: url)) { [weak self] resp in
                print("---------- urlResolve pid: \(pid) url: \(url) ---------")
                switch resp {
                case let .success(rst):
                    guard let json = try? JSON(data: rst.data) else {
                        print("urlResolve-json为nil")
                        return
                    }
                    print(json)
                    let rtn = json["rtn"].intValue
                    if rtn == 0 {
                        let taskInfo = json["taskInfo"]
                        let url = taskInfo["url"].stringValue
                        let name = taskInfo["name"].stringValue
                        let size = taskInfo["size"].intValue
                        
                        let infos = [TaskInfo(name: name, url: url, filesize: size)]
                        
                        self?.createTask(pid: pid, infos: infos)
                    } else {
                        print("状态异常-\(rtn)")
                    }
                    
                case let .failure(err):
                    print("err: \(err)")
                }
        }
    }

    func createTask(pid: String, infos: [TaskInfo]) {
        
        provider.request(.createTask(pid: pid, infos: infos)) { resp in
            print("---------- createTask pid: \(pid) ---------")
            
            switch resp {
            case let .success(rst):
                guard let json = try? JSON(data: rst.data) else {
                    print("createTask-json为nil")
                    return
                }
                
                if json["rtn"].intValue == 0 {
                    let tasks = json["tasks"].arrayValue
                    tasks.forEach { print($0) }
                }
            case let .failure(err):
                print("err: \(err)")
            }
        }
    }
}

